package com.kwlt.smc.rt;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springside.modules.test.spring.SpringTransactionalTestCase;

import com.kwlt.smc.dao.SmsSendDetailDao;
import com.kwlt.smc.entity.SmsSendDetail;
import com.kwlt.smc.util.ConUtils;


@ContextConfiguration(locations = { "/applicationContext.xml" })
public class RptSendDetail extends SpringTransactionalTestCase{
	
	@Autowired
	private SmsSendDetailDao smsSendDetailDao;
	
	@Test
	@Rollback(false)
	public void rtSms() throws Exception{
		List<SmsSendDetail> sList=this.getDate();
		int i=0;
		int m=0;
		List<Map<String,String>> moMapList=new ArrayList<Map<String,String>>();
		for(SmsSendDetail ssd :sList){
			Map<String,String> map=new HashMap<String, String>();
			String reports=ssd.getLocalMsgId()+","+ssd.getPhoneNum()+","+ssd.getRptValue()+","+ ConUtils.formatDate(ssd.getRptDate(),"yyyyMMddHHmmss");
			map.put("reports", reports);
			map.put("rptIp", "http://119.147.214.53:8080/sms/receiver/linan/5063");
			moMapList.add(map);
			i++;
			if(i==100){
				deliverRpt(moMapList);
				moMapList.clear();
				i=0;
				m++;
			}
		}
		if(moMapList.size()>0){
			deliverRpt(moMapList);
		}
		System.out.println(sList.size());
		System.out.println(m);
	}
	
	public void deliverRpt(List<Map<String,String>> moMapList) throws IOException {
		String rptIp=moMapList.get(0).get("rptIp");
		String strUrl ="";
		if(!StringUtils.isBlank(rptIp)){
			strUrl=rptIp;
		}
		final StringBuffer allReports= new StringBuffer();
		for(Map<String,String> map:moMapList){
			allReports.append(map.get("reports"));
			allReports.append(";");
		}
		if (allReports.toString().endsWith(";")) {
			allReports.setLength(allReports.length() - 1);
		}
		Map<String, String> paramentMap = new LinkedHashMap<String, String>() {
			{
				put("reports",allReports.toString());
			}
		};
		String result=sendHttpPostRequest(strUrl, paramentMap);
		if(StringUtils.isBlank(result)){
			result="1";//错误
		}
		System.out.println(strUrl+"\t"
				+  result+"\t"
				+ allReports.toString());
	}
	public static String sendHttpPostRequest(String strUrl,
			Map<String, String> paramentMap) {
		URL url;
		HttpURLConnection httpConn;
		StringBuffer sb = new StringBuffer();
		try {
			url = new URL(strUrl);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("content-type",
					"application/x-www-form-urlencoded");
			StringBuffer parament = new StringBuffer();
			for (Map.Entry<String, String> entry : paramentMap.entrySet()) {
				// System.out.println("key:" + entry.getKey() + "   value:" +
				// entry.getValue());
				if (StringUtils.isBlank(entry.getKey()))
					parament.append(URLEncoder.encode(entry.getValue(), "UTF-8")
							+ "&");
				else
					parament.append(entry.getKey() + "="
							+ URLEncoder.encode(entry.getValue(), "UTF-8")
							+ "&");
			}
			if (StringUtils.isBlank(parament.toString()))
				return "9999";
			if (parament.toString().endsWith("&")) {
				parament.setLength(parament.length() - 1);
			}
			httpConn.setRequestProperty("Content-Length",
					String.valueOf(parament.toString().getBytes().length));
			//System.out.println("para:" + parament.toString());
			httpConn.getOutputStream().write(parament.toString().getBytes());
			httpConn.getOutputStream().flush();
			httpConn.getOutputStream().close();
			//System.out.println("code:" + httpConn.getResponseCode());
			InputStream is = httpConn.getInputStream();
			int nRead;
			byte[] bBuffer = new byte[1024];
			do {
				nRead = is.read(bBuffer);
				if (nRead <= 0)
					break;
				sb.append(new String(bBuffer, 0, nRead, "utf-8"));
			} while (true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	public List<SmsSendDetail> getDate(){
		StringBuffer sql = new StringBuffer();
		sql.append("select LOCAL_MSG_ID,PHONE_NUMBER,RPT_VALUE,RPT_DATE from rpt_send_detail_20121202 where user='fuhaiys2' limit 0,1000");
		List<Object[]> list = smsSendDetailDao.query(sql.toString());
		List<SmsSendDetail> sList=new ArrayList<SmsSendDetail>();
		
		for(Object[] obj:list){
			SmsSendDetail ssd=new SmsSendDetail();
			ssd.setLocalMsgId(obj[0].toString());
			ssd.setPhoneNum(obj[1].toString());
			ssd.setRptValue(obj[2].toString());
			ssd.setRptDate(ConUtils.parseDate(obj[3].toString()));
			sList.add(ssd);
		}
		return sList;
	}
}
